﻿/**************************************************************
 * Copyright Eastmoney Corporation. All rights reserved.
 * 
 * Author: guitao(guitao@eastmoney.com) 
 * Create Date: 2020/6/18 10:38:32
 * Description:
 *          
 * Revision History:
 *      Date         Author               Description
 *              
***************************************************************/

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WorkerService.Sample
{
    public class TimeHostedService : IHostedService, IDisposable
    {
        private int _executionCount = 0;
        private readonly ILogger<TimeHostedService> _logger;
        private Timer _timer;
        private IServiceProvider _serviceProvider;

        public TimeHostedService(ILogger<TimeHostedService> logger,
            IServiceProvider provider)
        {
            _serviceProvider = provider;
            _logger = logger;
        }

        /// <summary>
        /// 在以下操作之前调用 StartAsync： 已配置应用的请求处理管道 (Startup.Configure)。 
        /// 已启动服务器且已触发 IApplicationLifetime.ApplicationStarted。
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("time hosted service running.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(5));

            return Task.CompletedTask;
        }
        /// <summary>
        /// StopAsync 中调用的任何方法都应及时返回。 但是，在请求取消后，将不会放弃任务 — 调用方等待所有任务完成。
        /// 如果应用意外关闭（例如，应用的进程失败），则可能不会调用 StopAsync。 
        /// 因此，在 StopAsync 中执行的任何方法或操作都可能不会发生。
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Hosted Service is stopping.");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            var count = Interlocked.Increment(ref _executionCount);

           _logger.LogInformation(
                "Timed Hosted Service is working. Count: {Count}", count);
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
}
